package com.ala4.oxcafe.boot.web;

import com.ala4.oxcafe.boot.utils.ExceptionUtil;
import com.ala4.oxcafe.domain.R;
import com.ala4.oxcafe.exception.BusinessException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Set;

/**
 * 统一异常处理
 *
 * @author PING
 * @version 1.0.0
 * @date 2025/8/4 12:44
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public R<?> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        String fullExceptionChain = ExceptionUtil.getFullExceptionChain(e);
        log.error("请求地址'{}',发生未知异常:\n{}", requestURI, fullExceptionChain, e);

        return R.fail(ExceptionUtil.getRootCause(e).getMessage(), requestURI, fullExceptionChain);
    }

    /**
     * 拦截业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public R<?> handleBusinessException(BusinessException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        String fullExceptionChain = ExceptionUtil.getFullExceptionChain(e);
        log.error("请求地址'{}',发生业务异常:\n{}", requestURI, fullExceptionChain, e);

        return R.fail(ExceptionUtil.getRootCause(e).getMessage(), requestURI, fullExceptionChain);
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public R<?> handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        String fullExceptionChain = ExceptionUtil.getFullExceptionChain(e);
        return R.fail(ExceptionUtil.getRootCause(e).getMessage(), requestURI, fullExceptionChain);
    }


    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public R<?> handleBindException(BindException e, HttpServletRequest request) {
        List<String> resultMessageList = e.getAllErrors().stream().map(ObjectError::getDefaultMessage).toList();
        return this.validException(resultMessageList, request, e);
    }

    /**
     * 自定义验证异常-请求入参为实体类, 嵌套类时调用
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<?> methodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {

        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> resultMessageList = fieldErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).toList();

        return this.validException(resultMessageList, request, e);
    }

    /**
     * 自定义验证异常-请求入参为list集合, 嵌套类时调用
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public R<?> handlerValidator(ConstraintViolationException e, HttpServletRequest request) {

        Set<ConstraintViolation<?>> constraintViolationSets = e.getConstraintViolations();
        List<String> resultMessageList = constraintViolationSets.stream().map(ConstraintViolation::getMessageTemplate).toList();

        return this.validException(resultMessageList, request, e);
    }

    private R<?> validException(List<String> resultMessageList, HttpServletRequest request, Exception e) {

        String message = resultMessageList.toString().substring(1, resultMessageList.toString().length() - 1);
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生自定义验证异常.", requestURI, e);

        String fullExceptionChain = ExceptionUtil.getFullExceptionChain(e);

        return R.fail(message, requestURI, fullExceptionChain);
    }


}
